import { operator } from "./op_enums";

/**
 * 自动从 source 中提取 key，并统一计算结果
 */
export const useTagResults = (
    value: any,
    op: operator,
    op_number?: number,
    retain?: number
): string | number => {
    // 处理无效值
    if (value === undefined || value === null) return 0.00;

    // 仅处理 number 类型
    if (typeof value === 'number') {

        if (op !== operator.NO && typeof op_number === 'number') {
            let result: number;

            switch (op) {
                case operator.Add:
                    result = value + op_number!;
                    break;
                case operator.Subtract:
                    result = value - op_number!;
                    break;
                case operator.Multiply:
                    result = value * op_number!;
                    break;
                case operator.Divide:
                    result = op_number === 0 ? value : value / op_number!;
                    break;
                default:
                    result = value;
            }

            return calculateResult(result, retain);
        }

        return calculateResult(value, retain);
    }

    // 非 number 类型直接返回原值
    return value;
};

//保留小数
const calculateResult = (value: any, retain: any): string | any => {
    if (typeof value !== "number" || typeof retain !== "number") {
        return value;
    } else {
        return value.toFixed(retain);
    }
}